package com.example.myapplication.fragment;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.R;
import com.example.myapplication.event.TTSWorkingEvent;
import com.example.myapplication.model.Word;
import com.example.myapplication.service.MusicService;
import com.example.myapplication.service.PlayListener;
import com.example.myapplication.utils.Preference;
import com.example.myapplication.utils.SQLiteHelper;
import com.example.myapplication.utils.TTSHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WordFragment  extends Fragment {

    private View mRootView;
    private MusicService.MusicController musicController;
    private SeekBar seekBar;
    private boolean update = true;
    private List<Word> mWordList = new ArrayList<>();
    private TextView wordTv;
    private TextView transTv;
    private TextView maskTv;
    private int currWord = 0;
    private ImageView btnToggle;

    private EditText idxStart;
    private EditText idxEnd;

    private boolean isPlaying = false;
    private boolean showTranslation = true;

    private TextView lableTv;
    private int delay;
    private String[] delayVal;



    public void setMusicController(MusicService.MusicController c) {
        musicController = c;
        musicController.setListener(new PlayListener() {
            @Override
            public void notifyProgress(final int pos,final int duration) {
                //TODO 将播放进度 更新到UI
                if(update) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            seekBar.setMax(duration);
//                            seekBar.setProgress(pos);
                        }
                    });
                }
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mRootView = inflater.inflate(R.layout.fragment_word, container, false);

        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        TTSHelper.prepare();

        delayVal = getResources().getStringArray(R.array.delay_array);
        delay = (int)(Float.parseFloat(delayVal[0].replace("s","") ) * 1000);

        RadioGroup radioGroup = mRootView.findViewById(R.id.word_db);
        RadioButton btnCET6 = mRootView.findViewById(R.id.cet6);
        RadioButton btnTOEFL = mRootView.findViewById(R.id.toefl);
        RadioButton btnPG = mRootView.findViewById(R.id.pg);

        RadioGroup wordOrder = mRootView.findViewById(R.id.word_order);
        RadioButton btnNormal = mRootView.findViewById(R.id.normal);
        RadioButton btnReverse = mRootView.findViewById(R.id.reverse);
        RadioButton btnRandom = mRootView.findViewById(R.id.random);

        Button btnSpeedAdd = mRootView.findViewById(R.id.speed_add);
        Button btnSpeedMinus = mRootView.findViewById(R.id.speed_minus);
        final TextView speedTv = mRootView.findViewById(R.id.speed);
        final Spinner delaySp = mRootView.findViewById(R.id.delay);

        delaySp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                delay = (int)(Float.parseFloat(delayVal[i].replace("s","") ) * 1000);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        lableTv = mRootView.findViewById(R.id.lable);


        View.OnClickListener speedListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float r = TTSHelper.getInstance().getSpeed();
                if(view.getId() == R.id.speed_add) {
                    speedTv.setText(TTSHelper.getInstance().setSpeed(r + 0.1f));
                } else if(view.getId() == R.id.speed_minus) {
                    speedTv.setText(TTSHelper.getInstance().setSpeed(r - 0.1f));
                }
            }
        };

        btnSpeedAdd.setOnClickListener(speedListener);
        btnSpeedMinus.setOnClickListener(speedListener);

        Button btnQuery = mRootView.findViewById(R.id.btn_query);
        ImageButton btnLeft = mRootView.findViewById(R.id.btn_left);
        ImageButton btnRight = mRootView.findViewById(R.id.btn_right);

        wordTv = mRootView.findViewById(R.id.word);
        transTv = mRootView.findViewById(R.id.translation);
        maskTv = mRootView.findViewById(R.id.mask);

        View.OnClickListener transListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchTransShow();
            }
        };

        transTv.setOnClickListener(transListener);
        maskTv.setOnClickListener(transListener);

        wordTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TTSHelper.getInstance().speak(wordTv.getText().toString());
            }
        });

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.getId() == R.id.btn_left) {
                    updateWordView(-1);
                } else if(v.getId() == R.id.btn_right) {
                    updateWordView(1);
                }
            }
        };

        btnLeft.setOnClickListener(onClickListener);
        btnRight.setOnClickListener(onClickListener);


        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String idx = idxStart.getText().toString();
                if(idx.equals(""))
                    idx = "1";
                Preference.getInstance().setIdxStart(Integer.parseInt(idx));

                idx = idxEnd.getText().toString();
                if(idx.equals(""))
                    idx = "1";
                Preference.getInstance().setIdxEnd(Integer.parseInt(idx));
                updateWords();
            }
        });

        wordOrder.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.normal:
                        Preference.getInstance().setWordOrder(1);
                        break;
                    case R.id.reverse:
                        Preference.getInstance().setWordOrder(2);
                        break;
                    case R.id.random:
                        Preference.getInstance().setWordOrder(3);
                        break;
                }
            }
        });

        int order = Preference.getInstance().getWordOrder();
        btnNormal.setChecked(order==1);
        btnReverse.setChecked(order==2);
        btnRandom.setChecked(order==3);


        seekBar = mRootView.findViewById(R.id.seek_bar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(seekBar.getProgress() < mWordList.size()) {
                    currWord = seekBar.getProgress();
                    wordTv.setText(mWordList.get(currWord).en);
                    transTv.setText(mWordList.get(currWord).getTranslation());
                    lableTv.setText((currWord+1) + "/" + mWordList.size());
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                update = false;
                setPlaying(false);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });


        btnToggle = mRootView.findViewById(R.id.play_toggle);

        btnToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mWordList.size() == 0) {
                    showTranslation = true;
                    switchTransShow();
                    transTv.setText("请先查询！");
                    return;
                }
                if(isPlaying) {
                    setPlaying(false);
                } else {
                    if(currWord < mWordList.size()) {
                        TTSHelper.getInstance().speak(mWordList.get(currWord++).en);
                    } else {
                        currWord = 0;
                        seekBar.setProgress(currWord);
                        TTSHelper.getInstance().speak(mWordList.get(currWord++).en);
                    }
                    setPlaying(true);
                }
            }
        });

        idxStart = mRootView.findViewById(R.id.idx_start);
        idxEnd = mRootView.findViewById(R.id.idx_end);

        idxStart.setText(   Preference.getInstance().getIdxStart() + "");
        idxEnd.setText(   Preference.getInstance().getIdxEnd() + "");

        idxStart.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                int idx = Integer.parseInt(idxStart.getText().toString());
                Preference.getInstance().setIdxStart(idx);
            }
        });

        idxEnd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                int idx = Integer.parseInt(idxEnd.getText().toString());
                Preference.getInstance().setIdxEnd(idx);
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.cet6:
                        Preference.getInstance().setWordDB("CET6");
                        break;
                    case R.id.toefl:
                        Preference.getInstance().setWordDB("TOEFL");
                        break;
                    case R.id.pg:
                        Preference.getInstance().setWordDB("Postgraduate");
                        break;
                }
            }
        });

        String db = Preference.getInstance().getWordDB();

        switch (db){
            case "CET6":
                btnCET6.setChecked(true);
                break;
            case "TOEFL":
                btnTOEFL.setChecked(true);
                break;
            case "Postgraduate":
                btnPG.setChecked(true);
                break;
        }
        return mRootView;
    }

    private void switchTransShow() {
        maskTv.setVisibility(showTranslation ? View.GONE : View.VISIBLE);
        transTv.setVisibility(showTranslation ? View.VISIBLE : View.GONE);
        showTranslation = !showTranslation;
    }

    private void updateWordView(int i) {
        if(currWord + i >= 0) {
            if((currWord + i) < mWordList.size() ) {
                currWord += i;
                wordTv.setText(mWordList.get(currWord).en);
                transTv.setText(mWordList.get(currWord).getTranslation());
                seekBar.setProgress(currWord);
            }
        }

    }

    private void updateWords() {
        mWordList = SQLiteHelper.getInstance().query(
                Preference.getInstance().getWordDB(),
                Preference.getInstance().getIdxStart(),
                Preference.getInstance().getIdxEnd());
        wordTv.setText("");
        transTv.setText("");
        seekBar.setMax(100);
        seekBar.setProgress(0);
        lableTv.setText("0/0");
        if(mWordList.size()>0) {
            wordTv.setText(mWordList.get(0).en);
            transTv.setText(mWordList.get(0).getTranslation());
            seekBar.setMax(mWordList.size());
            lableTv.setText("1/"+mWordList.size());
        }
        currWord = 0;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTTSWorking(TTSWorkingEvent event) {
        if (!isPlaying) {
            return;
        }
        seekBar.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(currWord < mWordList.size()) {
                    seekBar.setProgress(currWord);
                    TTSHelper.getInstance().speak(mWordList.get(currWord).en);
                    currWord++;
                } else {
                    seekBar.setProgress(mWordList.size());
                    setPlaying(false);
                }
            }
        }, delay);

    }

    private void setPlaying(boolean what) {
        isPlaying = what;
        btnToggle.setImageDrawable(getResources().getDrawable(isPlaying ? R.drawable.ic_pause : R.drawable.ic_play));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
